<template>
  <a-config-provider
    :theme="{
      algorithm: isDark ? darkAlgorithm : defaultAlgorithm,
      token: {
        colorPrimary: globalConfig.primaryColor,
      },
    }"
  >
    <router-view></router-view>
  </a-config-provider>
</template>

<script setup lang="ts">
import { theme } from 'ant-design-vue'
import { PRIMARY_COLOR_KEY, PRIMARY_COLOR, DARK_THEME } from '@/const/theme'
import { setCssProperty, getAppCssVariables, addThemeClass } from '@/app/style'
import useConfigStore from '@/store/modules/config'

const configStore = useConfigStore()

const globalConfig = computed(() => configStore.globalConfig)
const isDark = computed(() => configStore.isDark)

const { defaultAlgorithm, darkAlgorithm } = theme

onMounted(() => initStyle())

function initStyle() {
  setCssProperty('--app-primary-color', PRIMARY_COLOR)
  const cssVars = transformCssVars(getAppCssVariables())
  configStore.setConfig(PRIMARY_COLOR_KEY, cssVars[PRIMARY_COLOR_KEY])

  isDark.value && addThemeClass(DARK_THEME)
}

function transformCssVars(vars: Record<string, string>): Record<string, string> {
  return Object.fromEntries(
    Object.entries(vars).map(([key, value]) => {
      const cleaned = key.replace(/^--app-/, '').replace(/^--/, '')
      const camelKey = cleaned.replace(/-([a-z])/g, (_, char) => char.toUpperCase())
      return [camelKey, value.trim()]
    }),
  )
}
</script>
